<template>
  <div class="merchants-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商家管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加商家
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索商家名称、联系人"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="审核状态" clearable>
              <el-option label="待审核" value="pending" />
              <el-option label="已通过" value="approved" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.type" placeholder="商家类型" clearable>
              <el-option label="餐饮" value="restaurant" />
              <el-option label="快餐" value="fastfood" />
              <el-option label="饮品" value="beverage" />
              <el-option label="甜品" value="dessert" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="exportData">导出</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 商家列表 -->
      <el-table
        :data="merchantList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="商家信息" width="300">
          <template #default="scope">
            <div class="merchant-info">
              <el-avatar :src="scope.row.avatar" size="small" />
              <div class="info-text">
                <div class="name">{{ scope.row.name }}</div>
                <div class="contact">{{ scope.row.contactPerson }} - {{ scope.row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storeCount" label="店铺数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusColor(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewMerchant(scope.row)"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              type="success"
              size="small"
              @click="approveMerchant(scope.row)"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              type="danger"
              size="small"
              @click="rejectMerchant(scope.row)"
            >
              拒绝
            </el-button>
            <el-dropdown v-else @command="handleCommand">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'edit', row: scope.row}">编辑</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'stores', row: scope.row}">店铺管理</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'disable', row: scope.row}" divided>禁用</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑商家对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="商家类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择商家类型">
            <el-option label="餐饮" value="restaurant" />
            <el-option label="快餐" value="fastfood" />
            <el-option label="饮品" value="beverage" />
            <el-option label="甜品" value="dessert" />
          </el-select>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <el-input v-model="form.businessLicense" placeholder="请输入营业执照号" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入商家描述" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 商家详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="商家详情"
      width="800px"
    >
      <div v-if="currentMerchant" class="merchant-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商家名称">{{ currentMerchant.name }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentMerchant.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentMerchant.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentMerchant.email }}</el-descriptions-item>
          <el-descriptions-item label="商家类型">{{ getTypeText(currentMerchant.type) }}</el-descriptions-item>
          <el-descriptions-item label="营业执照">{{ currentMerchant.businessLicense }}</el-descriptions-item>
          <el-descriptions-item label="店铺数量">{{ currentMerchant.storeCount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(currentMerchant.status)">
              {{ getStatusText(currentMerchant.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间" :span="2">{{ currentMerchant.createTime }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">{{ currentMerchant.address }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ currentMerchant.description }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const submitting = ref(false)
const formRef = ref()

const searchForm = reactive({
  keyword: '',
  status: '',
  type: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const form = reactive({
  id: null,
  name: '',
  contactPerson: '',
  phone: '',
  email: '',
  type: '',
  businessLicense: '',
  address: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入商家名称', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择商家类型', trigger: 'change' }],
  businessLicense: [{ required: true, message: '请输入营业执照号', trigger: 'blur' }]
}

const merchantList = ref([])
const selectedMerchants = ref([])
const currentMerchant = ref(null)

const dialogTitle = computed(() => form.id ? '编辑商家' : '添加商家')

// 模拟数据
const mockMerchants = [
  {
    id: 1,
    name: '麦当劳餐饮有限公司',
    contactPerson: '张经理',
    phone: '13800138001',
    email: 'mcdonald@example.com',
    type: 'fastfood',
    businessLicense: '91110000123456789X',
    address: '北京市朝阳区建国路88号',
    description: '全球知名快餐连锁品牌',
    storeCount: 15,
    status: 'approved',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    createTime: '2023-01-15 10:30:00'
  },
  {
    id: 2,
    name: '星巴克咖啡',
    contactPerson: '李经理',
    phone: '13800138002',
    email: 'starbucks@example.com',
    type: 'beverage',
    businessLicense: '91110000123456789Y',
    address: '北京市海淀区中关村大街1号',
    description: '全球知名咖啡连锁品牌',
    storeCount: 8,
    status: 'approved',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    createTime: '2023-02-20 14:20:00'
  },
  {
    id: 3,
    name: '小龙坎火锅',
    contactPerson: '王经理',
    phone: '13800138003',
    email: 'xiaolongkan@example.com',
    type: 'restaurant',
    businessLicense: '91110000123456789Z',
    address: '北京市西城区西单大街100号',
    description: '知名火锅连锁品牌',
    storeCount: 3,
    status: 'pending',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    createTime: '2023-12-10 09:15:00'
  }
]

const loadMerchants = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    merchantList.value = mockMerchants
    pagination.total = mockMerchants.length
  } catch (error) {
    ElMessage.error('加载商家列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadMerchants()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    type: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedMerchants.value = selection
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadMerchants()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadMerchants()
}

const showAddDialog = () => {
  resetForm()
  dialogVisible.value = true
}

const viewMerchant = (merchant) => {
  currentMerchant.value = merchant
  detailVisible.value = true
}

const approveMerchant = async (merchant) => {
  try {
    await ElMessageBox.confirm(`确定要通过商家"${merchant.name}"的审核吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    merchant.status = 'approved'
    ElMessage.success('审核通过成功')
  } catch (error) {
    // 用户取消
  }
}

const rejectMerchant = async (merchant) => {
  try {
    await ElMessageBox.confirm(`确定要拒绝商家"${merchant.name}"的审核吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    merchant.status = 'rejected'
    ElMessage.success('审核拒绝成功')
  } catch (error) {
    // 用户取消
  }
}

const handleCommand = (command) => {
  const { action, row } = command
  
  switch (action) {
    case 'edit':
      editMerchant(row)
      break
    case 'stores':
      ElMessage.info('跳转到店铺管理页面')
      break
    case 'disable':
      disableMerchant(row)
      break
  }
}

const editMerchant = (merchant) => {
  Object.assign(form, merchant)
  dialogVisible.value = true
}

const disableMerchant = async (merchant) => {
  try {
    await ElMessageBox.confirm(`确定要禁用商家"${merchant.name}"吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ElMessage.success('禁用成功')
  } catch (error) {
    // 用户取消
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        if (form.id) {
          ElMessage.success('编辑成功')
        } else {
          ElMessage.success('添加成功')
        }
        
        dialogVisible.value = false
        loadMerchants()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const resetForm = () => {
  Object.assign(form, {
    id: null,
    name: '',
    contactPerson: '',
    phone: '',
    email: '',
    type: '',
    businessLicense: '',
    address: '',
    description: ''
  })
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const exportData = () => {
  ElMessage.success('导出功能开发中...')
}

const getStatusColor = (status) => {
  const colorMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return colorMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return textMap[status] || '未知'
}

const getTypeColor = (type) => {
  const colorMap = {
    'restaurant': 'primary',
    'fastfood': 'success',
    'beverage': 'warning',
    'dessert': 'info'
  }
  return colorMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    'restaurant': '餐饮',
    'fastfood': '快餐',
    'beverage': '饮品',
    'dessert': '甜品'
  }
  return textMap[type] || '未知'
}

onMounted(() => {
  loadMerchants()
})
</script>

<style scoped>
.merchants-page {
  padding: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.merchant-info {
  display: flex;
  align-items: center;
}

.info-text {
  margin-left: 10px;
}

.name {
  font-weight: bold;
  margin-bottom: 4px;
}

.contact {
  font-size: 12px;
  color: #999;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.merchant-detail {
  padding: 20px 0;
}
</style> 